const UserService = require("../services/UserService");
const gravatar = require("gravatar");
const bcrypt = require("bcrypt");
const JWT = require(".././utils/jwt");
const UserController = {
  // 注册
  register: async (req, res) => {
    let { email, password, name, identity } = req.body;
    // 生成头像 邮箱+options
    const avatar = gravatar.url(email, {
      s: "200", //大小
      r: "pg", //级别
      d: "mm", //默认值
    });
    let user = await UserService.findUser(email);
    console.log(user);
    if (user) {
      res.apiResponse(new Error("邮箱已被注册"));
      return;
    }
    // 生成盐值;
    bcrypt.genSalt(10, function (err, salt) {
      // 哈希处理密码，
      bcrypt.hash(password, salt, async function (err, hash) {
        // Store hash in your password DB.
        if (err) throw err;
        await UserService.add({
          name,
          email,
          avatar: avatar,
          password: hash,
          identity,
        });
        res.apiResponse({ message: "注册成功" });
      });
    });
  },
  // 登录
  login: async (req, res) => {
    let { email, password } = req.body;
    // 查询用户
    let user = await UserService.findUser(email);
    if (!user) {
      res.apiResponse(new Error("用户不存在"));
      return;
    }
    // 密码匹配
    let match = await bcrypt.compare(password, user.password);
    if (!match) {
      res.apiResponse(new Error("密码错误"));
      return;
    }
    // 生成token
    const token = JWT.generate(
      {
        _id: user._id,
        username: user.name,
        avatar: user.avatar,
        identity: user.identity,
      },
      "1d"
    );
    //校验是否生成
    if (!token) {
      res.apiResponse(new Error("token is not valid"));
      return;
    }
    res.apiResponse({ message: "登录成功", token: "Bearer " + token });
  },
  userInfo: async (req, res) => {
    console.log(req.user);
    let { _id, name, email, identity, avatar } = req.user;

    res.apiResponse({
      message: "success",
      _id,
      name,
      email,
      identity,
      avatar,
    });
  },
};

module.exports = UserController;
